<%@ page language="java" import="java.util.*,org.apache.struts2.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"   %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE HTML>
<html>
<head>
	<title></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="<%=basePath %>/assets/css/dpl-min.css" rel="stylesheet" type="text/css" />
	<link href="<%=basePath %>/assets/css/bui-min.css" rel="stylesheet" type="text/css" />
    <link href="<%=basePath %>/assets/css/page-min.css" rel="stylesheet" type="text/css" /> 
	<style type="text/css">
	 #grid,#btnSave,.row{
	 	margin-top:10px;
	 	margin-left:20px;
	 }
	 #loding{
	 	width:100%;
	 	height:100%;
	 	background:transparent;
	 	z-index:2000;
	 	text-align: center;
	 	display: none;
	 	position: absolute;
	 }
	/**内容超出 出现滚动条 **/
    .bui-stdmod-body{
      overflow-x : hidden;
      overflow-y : auto;
    }

   	.form-horizontal , .h3_title{
   		margin-left:30px;
   	}
   	#upload_logo {
   		margin-top:70px;
   		margin-left:120px;
   		margin-bottom: 10px;
   		width:50%;
   	}
   	#upload_other{
   		margin-top:-30px;
   		margin-left:120px;
   		margin-bottom: 10px;
   		width:50%;
   	}
   	
	</style>
</head>
<body>
    <div id="grid" ></div>
	
    <div id="content" class="hide">
	<form id="J_Form" class="form-horizontal" method="post">
	<h3 class="h3_title">产品信息变更</h3>
	  <input type="hidden" name="id" id="id">
      <div class="control-group">
        <label class="control-label"><s>*</s>产品名称:</label>
        <div class="controls">
          <input name="name" type="text" class="input-normal" data-rules="{required : true}"  >
        </div>
      </div>
      
      <div class="control-group" >
        <label class="control-label"><s>*</s>产品介绍:</label>
        <div class="controls  control-row-auto">
          <textarea name="product_introduce"  class="control-row4 input-large" data-rules="{required : true}"></textarea>
        </div>
      </div>
      
      <div class="control-group">
        <label class="control-label"><s>*</s>产品价格:</br><a></a></label>
        <div class="controls">
          <input type="text" class="input-normal" name="super_market_price" data-rules="{number:true , required : true ,maxlength:5}" >
          <a style="color:red;font-size:12px;">元</a>
          <span class="auxiliary-text">超市价格</span>
        </div>
      </div>
      
      <div class="control-group">
        <label class="control-label"><s>*</s>产品价格:</label>
        <div class="controls">
          <input name="local_price" type="text" class="input-normal" data-rules="{number:true , required : true ,maxlength:5}"  >
          <a style="color:red;font-size:12px;">元</a>
          <span class="auxiliary-text">本店价格</span>
        </div>
      </div>
      
      <div class="control-group">
        <label class="control-label"><s>*</s>产品图片:
        	<br/>
        	<span class="auxiliary-text">主页显示&nbsp;&nbsp;</span>
        </label>
        <div class="controls">
        	<img src="" id="viewimg" style="width:100px;height:100px;border:1px solid #ddd;">
	      	<div id="J_Uploader_logo"></div>
      	</div>
      	<input id="img_logo" type="hidden" name="img_logo" value=""  data-rules="{required : true}" data-messages="{required:'请上传图片'}">
      </div>
      
      <div class="control-group" id="sub_sort_id_div">
        <label class="control-label"><s>*</s>属于子类:</label>
        <div class="controls  control-row-auto">
			<select id="sub_sort_select" disabled="disabled" onchange="getSelectedToSub_id()">
			</select>
        </div>
        <a onclick="getSubSort()" style="margin-left:5px;">获取资源</a>
        <input name="sub_sort_id"  type="hidden" value="" data-rules="{required : true}" data-messages="{required:'请选择子类'}" id="sub_sort_id"/>
        <span id="select_subsort_state" Style="display:none;"></span>
      </div>
      
      <div class="control-group">
        <label class="control-label"><s>*</s>属于商户:</label>
        <div class="controls  control-row-auto">
			<select id="merchant_select" disabled="disabled" onchange="getSelectedToMerchant_id()">
			</select>
        </div>
        <a onclick="getMerchant()" style="margin-left:5px;">获取资源</a>
        <input name="merchant_id"  type="hidden" value="" data-rules="{required : true}" data-messages="{required:'请选择商户'}" id="merchant_id"/>
        <span id="select_merchant_state" Style="display:none;"></span>
      </div>
      
      <div class="control-group">
        <label class="control-label"><s>*</s>是否热销:</label>
        <div class="controls">
			<input type="radio" name="is_hot" value="是"> 是
            <input type="radio" name="is_hot" value="否" checked="checked" > 否
        </div>
      </div>
      
      <div class="control-group">
        <label class="control-label"><s>*</s>产品图片集:
        	<br/>
        	<span class="auxiliary-text">产品介绍页面显示</span>
        </label>
        <div class="controls">
	      	<div id="J_Uploader_other"></div>
      	</div>
      	<input id="img_other" type="hidden" name="img_other" value="">
      </div>
		<hr id="foot">
    </form>
    </div>
</body>
	<script type="text/javascript" src="<%=basePath %>/assets/js/jquery-1.8.1.min.js"></script>
	<script type="text/javascript" src="<%=basePath %>/assets/js/bui.js"></script>
	<script type="text/javascript" src="<%=basePath %>/assets/js/config.js"></script>
    <script type="text/javascript">
    	//设定BUI视图变量
    	var Grid = BUI.Grid;
    	//设定BUI数据变量
        var Data = BUI.Data;
        //获取数据
        var Store = Data.Store;
        //定义columns并且初始化
        var columns = [
          //table columns
          {title : '产品名称',dataIndex :'name',elCls : 'center',width:'30%'},
          {title : '超市价格(元)',dataIndex :'super_market_price',elCls : 'center',width:'20%' ,renderer : function(value){
                  return '<a style="color:red;font-size:16px;">'+value+'</a>';
                }},
          {title : '本店价格(元)',dataIndex :'local_price',elCls : 'center',width:'20%',renderer : function(value){
                  return '<a style="color:red;font-size:16px;">'+value+'</a>';
                }},
          {title : '属于子类',dataIndex :'sub_sort_name',elCls : 'center',width:'25%'},
          {title : '产品Logo',dataIndex :'img_logo',elCls : 'center',renderer : function(value){
                  return '<a class="hover-view-img" title="'+value+'" >产品图片</a>';
                }},
          {title : '是否热销',dataIndex :'is_hot',elCls : 'center'},
          {title : '添加时间',dataIndex :'add_date',elCls : 'center',width:150},
		  {title : '操作',elCls : 'center',renderer : function(){
		    return '<span class="grid-command btn-edit">编辑</span><a href="#" class="btn-del" style="color:red;">删除</a>';
		  }},
        ];
        
        //定义store并且通过AJAX获取数据
        var store = new Store({
        	//AJAX 提交路劲
            url : '<%=basePath %>/Json/Product',
            //自动加载数据
            autoLoad:true,
            //从第0个元素开始获取信息 
            start:0,
            //配置分页数目,后台相当于limit参数
            pageSize:15
            
          });

		
		//定义编辑器并且设定自定义按钮
		var editing = new Grid.Plugins.DialogEditing({
		 	//设置隐藏的Dialog内容
            contentId : 'content',
            //触发显示Dialog的样式
            triggerCls : 'btn-edit',
            //编辑器 
            editor : {
              width:'90%',
              height:350,
              elCls : 'editor',
              //编辑器标题
              title : '内容编辑',
              //设置自定义按钮
              buttons : [
              	//确定按钮
              	{
              		text:'确定',
              		elCls : 'button button-primary',
              		handler : function(ev){
              			GetSuccessUrl();
						//实现ajax数据提交
						$.ajax({
							type:"post",
							dataType:"json",
							data:{
								'id':editing.get('form').getFieldValue('id'),
								'name':editing.get('form').getFieldValue('name'),
								'product_introduce':editing.get('form').getFieldValue('product_introduce'),
								'super_market_price':editing.get('form').getFieldValue('super_market_price'),
								'local_price':editing.get('form').getFieldValue('local_price'),
								'img_logo':$("#img_logo").val(),
								'sub_sort_id':$("#sub_sort_id").val(),
								'merchant_id':$("#merchant_id").val(),
								'is_hot':editing.get('form').getFieldValue('is_hot'),
								'img_other' : GetSuccessUrl()
							},
							url:"<%=basePath %>/Product_JEdit",
							beforeSend: function(XMLHttpRequest){
								//显示稍等
								$("#loding").css("display","block");
							},
							success: function(data){
								//成功并且收到信息
								if(data==1){
									$("#loding").css("display","none");
									//隐藏稍等窗口
									BUI.Message.Alert('恭喜您,编辑成功!',function(){
										refreshFunction();
									},'success');
									//刷新
								}else{
									$("#loding").css("display","none");
									//隐藏稍等窗口
									BUI.Message.Alert('编辑失败，请重试！',function(){
										refreshFunction();
									},'error');
								}
							},
							error: function(status){
								if (status == "timeout")
				                {
				                	$("#loding").css("display","none");
				                	BUI.Message.Alert('请求超时，请重试!',function(){
										refreshFunction();
									},'error');
				                }else{
				                	$("#loding").css("display","none");
				                	//如果出别的错
									BUI.Message.Alert('系统错误，请跟管理员联系！',function(){
										refreshFunction();
									},'error');
				              	}
							}
						});
						//消失弹出窗口
						this.hide();
              		},
              	},
              	//取消按钮
              	{
              		text:'取消',
              		elCls : 'button',
              		handler : function(){
              			this.hide();
              		}
              	}
              ]
            }
          });
		
		//把每个行的内容隐藏起来点击后显示功能
		var cascade = new Grid.Plugins.Cascade({
  		    renderer : function(record){
  		    	var res="<div style='padding-left:40px;padding-top:10px;'><h2>产品基本信息</h2><p style='padding-left:40px;'>产品ID : "+record.id+"</br> 商户名称 : "+ record.merchant_name + " </p></div>";
  		    	res+="<hr><div style='padding-left:40px;padding-top:10px;'><h2>详情信息</h2><p style='padding-left:40px;'>"+ record.product_introduce + "</p></div>";
  		    	var img_other = (record.img_other).split("|");
  		    	res+="<hr><div style='padding-left:40px;'><h2>产品介绍图片</h2></br>";
  		    	for(var i=0;i<img_other.length;i++){
  		    		//第一个图片么没有padding-left:10px
					res+="<img src='<%=basePath %>"+img_other[i]+"' style='width:100px;height:100px;padding-left:40px;padding-top:10px;'>";
  		    	}
  		    	res+="<hr></div>";
  			    return res;
  		    }
        });
        
        
        
        //定义视图并且设置视图配置
        var grid = new Grid.Grid({
        	//显示div的id
            render:'#grid',
            //宽度
            width:'99.7%',
            //加载columns
            columns : columns,
            //加载数据时显示屏蔽层
            loadMask: true, 
            //加载store
            store: store,
            //给grid加载CheckSelection和编辑器
            plugins : [Grid.Plugins.RowNumber,editing,cascade],
            // 底部工具栏
            bbar:{
                // pagingBar:表明包含分页栏
                pagingBar:true,
            },
            // 顶部工具栏
            tbar:{
		      items : [
		      	//添加刷新按钮
		      	{
			        btnCls : 'button button-small',
			        text : '<i class="icon-refresh" tyle="color:blue"></i>刷新',
			        listeners : {
			          'click' : refreshFunction
			        }
		      	}
		      ]
		    }
        });
        
        //item点击事件
        grid.on('itemclick beforeitemsshow',function(ev){

	        var sender = $(ev.domTarget);
	        //获取点击的item
	        var item = ev.item;
	        //点击删除操作
	        if(sender.hasClass('btn-del')){
	        	//执行删除函数
	        	delFunction(item);
	        }else if(sender.hasClass('btn-edit')){
	        	//初始化编辑器
	        	init_edit(item);
	        }
        });
        
        //加载grid
        grid.render();
        //刷新函数
        function refreshFunction(){
        	location.reload();
        }
        
        //上传文件
       	BUI.use('bui/uploader',function (Uploader) {
		       var uploader = new Uploader.Uploader({
		       render: '#J_Uploader',
		       url: '<%=basePath%>/Merchant_JUpload',
		       rules: {
		         //文的类型
		         ext: ['.png,.jpg','文件类型只能为{0}'],
		         //上传的最大个数
		         max: [1, '文件的最大个数不能超过{0}个'],
		         //文件大小的最小值,这个单位是kb
		         minSize: [0, '文件的大小不能小于{0}KB'],
		         //文件大小的最大值,单位也是kb
		         maxSize: [1024, '文件大小不能大于1M']
		       },
		       isSuccess: function(res){
		       		$("#viewimg").attr("src","<%=basePath%>/"+res[0].url);
		       		$("#viewimg").attr("value",res[0].url);
		       }
		      }).render();
	    });
	    
	    //鼠标提示
		BUI.use('bui/tooltip',function (Tooltip) {
			var tips = new Tooltip.Tips({
	        	tip : {
		          trigger : '.hover-view-img', //出现此样式的元素显示tip
		          alignType : 'bottom-left', //默认方向
		          titleTpl : '<img src="<%=basePath %>/{title}">',
		          offset : 10 //距离左边的距离
		        }
		      });
	      tips.render();
		});
		
		var queue = null;
	    //上传图片
		BUI.use('bui/uploader',function (Uploader) {
			
			//带图片预览的主题
			  Uploader.Theme.addTheme('mytheme', {
			    elCls: 'imageViewTheme',
			    queue:{
			      resultTpl: {
			          'default': '<div class="default">{name}</div>',
			          'success': '<div data-url="{url}" class="success_url"><img src="<%=basePath%>{url}" title="{name}" style="width:100%;height:100%;"></div>',
			          'error': '<div class="error"><span title="{name}">{msg}</span></div>',
			          'progress': '<div class="progress"><div class="bar" style="width:{loadedPercent}%"></div></div>'
			      }
			    }
			  });
			  
		     //产品logo上传
		     var uploader_logo = new Uploader.Uploader({

		       text:'更改图片',
			   //给upload div 添加一个id标签
			   elAttrs :{id : 'upload_logo'},
			   //读取要放到的div
		       render: '#J_Uploader_logo',
		       //在那个元素前面
		       elBefore : '#sub_sort_id_div',
		       //获取数据地址
		       url: '<%=basePath%>/Product_JUploadProductLogo',
		       //验证文件
		       rules: {
		         //文的类型
		         ext: ['.png,.jpg','文件类型只能为{0}'],
		         //上传的最大个数
		         max: [1, '<br/>只允许上传{0}个图片,此图片将不上传!'],
		         //文件大小的最小值,这个单位是kb
		         minSize: [0, '文件的大小不能小于{0}KB'],
		         //文件大小的最大值,单位也是kb
		         maxSize: [1024, '文件大小不能大于1M']
		       },
		       multiple:false,
		       //成功返回的函数
		       isSuccess: function(res){
		       		$("#viewimg").css("display","block");
		       		$("#viewimg").attr("src","<%=basePath%>/"+res[0].url);
		       		$("#img_logo").attr("value",res[0].url);
		       		return true;
		       }
		      }).render();
		      
		      
		     //产品介绍图片集上传
		     var uploader_other = new Uploader.Uploader({
		       //指定使用主题
        	   theme: 'mytheme',
		       //给upload div 添加一个id标签
			   elAttrs :{id : 'upload_other'},
			   //给upload div 添加一个id标签
		       render: '#J_Uploader_other',
		       //在那个元素前面
		       elBefore : '#foot',
		       //获取数据地址
		       url: '<%=basePath%>/Product_JUploadProductImgOther',
		       //验证文件
		       rules: {
		         //文的类型
		         //上传的最大个数
		         max: [9, '只允许上传{0}个图片,此图片将不上传!'],
		         //文件大小的最小值,这个单位是kb
		         minSize: [0, '文件的大小不能小于{0}KB'],
		         //文件大小的最大值,单位也是kb
		         maxSize: [1024, '文件大小不能大于1M']
		       }
		      }).render();
		      //获取上传文件的对列
		      queue = uploader_other.get('queue');
		   });
		
         //获取子类
         function getSubSort(){
         	  //先清空
         	  $("#sub_sort_select").empty();
         	  //加载子类
			  $.ajax({
	             type: "GET",
	             url: "<%=basePath%>/SubSort_JGetNameAndId",
	             dataType: "json",
	             beforeSend:function(XMLHttpRequest){
	             	$("#select_subsort_state").css("dispaly","block");
	             	$("#sub_sort_select").attr("disabled","disabled");
	             },
	             success: function(data){
	             	if(data.length==0){
	             		$("#select_subsort_state").css("display","block");
	             		$("#select_subsort_state").append("<a style='color:red;margin-left:10px;'>子类为空,请先添加子类!</a>");
	             	}else{
		           		for(var i=0;i<data.length;i++){
		           			if(data[i].id==$("#sub_sort_id").val()){
		           				$("#sub_sort_select").append("<option value ='"+data[i].id+"' selected='selected' >"+data[i].name+"</option>");
		           			}else{
		           				$("#sub_sort_select").append("<option value ='"+data[i].id+"'>"+data[i].name+"</option>");
		           			}
		           		}
	           		}
	           		$("#sub_sort_select").removeAttr("disabled");
	             },
	             error:function(XMLHttpRequest, textStatus, errorThrown){
	             		$("#select_subsort_state").css("display","block");
	             		$("#select_subsort_state").append("<a style='color:red;margin-left:10px;'>发生错误,请联系管理员!</a>");
	             }
	          });
         }
         
         //获取商户
         function getMerchant(){
              //先清空
         	  $("#merchant_select").empty();
         	  //加载商户
			  $.ajax({
	             type: "GET",
	             url: "<%=basePath%>/Merchant_JGetNameAndId",
	             dataType: "json",
	             beforeSend:function(XMLHttpRequest){
	             	$("#merchant_select").attr("disabled","disabled");
	             	$("#select_merchant_state").css("dispaly","block");
	             },
	             success: function(data){
	             	if(data.length==0){
	             		$("#select_merchant_state").css("display","block");
	             		$("#select_merchant_state").append("<a style='color:red;margin-left:10px;'>商户表为空,请先添加商户!</a>");
	             	}else{
		           		for(var i=0;i<data.length;i++){
		           			if(data[i].id==$("#merchant_id").val()){
		           				$("#merchant_select").append("<option value ='"+data[i].id+"' selected='selected'>"+data[i].merchant_name+"</option>");
		           			}else{
		           				$("#merchant_select").append("<option value ='"+data[i].id+"'>"+data[i].merchant_name+"</option>");
		           			}
		           		}
	           		}
	           		$("#merchant_select").removeAttr("disabled");
	             },
	             error:function(XMLHttpRequest, textStatus, errorThrown){
	             		$("#select_merchant_state").css("display","block");
	             		$("#select_merchant_state").append("<a style='color:red;margin-left:10px;'>发生错误,请联系管理员!</a>");
	             }
	          });
         }
         
         //获取以选择给Root_id
         function getSelectedToSub_id(){
         	var res=$("#sub_sort_select option:selected").val();
         	if(res!=0){
         		$("#sub_sort_id").val(res);
         	}else{
         		$("#sub_sort_id").val("");
         	}
         }
         
         //获取以选择给Root_id
         function getSelectedToMerchant_id(){
         	var res=$("#merchant_select option:selected").val();
         	if(res!=0){
         		$("#merchant_id").val(res);
         	}else{
         		$("#merchant_id").val("");
         	}
         }
         
         //获取已确定上传的图片地址
         function GetSuccessUrl(){
         	var img_other_val="";
         	for(var i=0;i<$(".success_url").length;i++){
         		if(i==0){
         			img_other_val=$(".success_url:eq("+i+")").attr("data-url");
         		}else{
         			img_other_val+="|"+$(".success_url:eq("+i+")").attr("data-url");
         		}
         	}
         	return img_other_val;
         }
         
        //删除函数
        function delFunction(item){
        	BUI.Message.Confirm('你确定删除此数据吗?',function(){
          		setTimeout(function(){
          			//实现ajax数据提交
						$.ajax({
							type:"post",
							dataType:"json",
							data:{
								'id':item.id,
							},
							url:"<%=basePath %>/Product_JDelete",
							beforeSend: function(XMLHttpRequest){
								//显示稍等
								$("#loding").css("display","block");
							},
							success: function(data){
								//成功并且收到信息
								if(data==1){
									$("#loding").css("display","none");
									//隐藏稍等窗口
									BUI.Message.Alert('恭喜您,编辑成功!',function(){
										refreshFunction();
									},'success');
								}else{
									$("#loding").css("display","none");
									//隐藏稍等窗口
									BUI.Message.Alert('删除失败，请重试!',function(){
										refreshFunction();
									},'error');
								}
							},
							error: function(XMLHttpRequest, textStatus, errorThrown){
								if (textStatus == "timeout")
				                {
				                	$("#loding").css("display","none");
				                    BUI.Message.Alert('请求超时，请重试!',function(){
										refreshFunction();
									},'error');
				                }else{
				                	$("#loding").css("display","none");
				                	//如果出别的错
									BUI.Message.Alert('系统错误，请跟管理员联系！'+errorThrown,function(){
										refreshFunction();
									},'error');
				              	}
							}
						});
          		});
        	},'question');
        }
         
         //初始化编辑器
         function init_edit(item){
         	//产品logo获取信息
         	$("#viewimg").attr("src","<%=basePath%>"+item.img_logo); 
         	//初始化编辑其他图片
         	var res =  (item.img_other).split("|");

			if(res != ''){
	         	var list = new Array();
	         	//设置文件的回显   
	         	for(var i=0;i<res.length;i++){
	         		var temp = {
	         			success: true,
	         			name: "产品介绍照片",
	         			url:res[i],
	         			ext:'.jpg'
	         		};
	         		list.push(temp);
	         	}
	         	queue.setItems(list);
	         }
         }
    </script>
</html>
